package com.chain.BrotherExchange.viewmodel;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.ImageView;

import com.chain.BrotherExchange.data.DataRepository;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.Appeal;
import com.chain.BrotherExchange.utils.Androids;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * 反馈或申诉
 */
public class FeedbackViewModel extends AndroidViewModel {

    private int uid = Androids.LocalConfig.getUid();
    private String token = Androids.LocalConfig.getToken();

    private List<String> mImageList = new ArrayList<>();
    private MutableLiveData<Resource<Integer>> mUpdateImageLiveData;
    private MutableLiveData<Resource<Appeal>> mLegalTenderAppeal;

    public FeedbackViewModel(@NonNull Application application) {
        super(application);
        mLegalTenderAppeal = new MutableLiveData<>();
        mUpdateImageLiveData = new MutableLiveData<>();
    }

    public MutableLiveData<Resource<Appeal>> legalTenderAppeal(
            int tokenId, String orderId, int opt, String tokenName, String remarks) {

        if (TextUtils.isEmpty(remarks)) {
            mLegalTenderAppeal.setValue(Resource.error("请填写申诉原因"));
            return mLegalTenderAppeal;
        }

        if (mImageList.isEmpty()) {
            mLegalTenderAppeal.setValue(Resource.error("请选择图片"));
            return mLegalTenderAppeal;
        }

        String images = new Gson().toJson(mImageList);
        mLegalTenderAppeal.setValue(Resource.loading());
        String tokenIdStr = String.valueOf(tokenId);
        DataRepository.get().legalTenderAppeal(uid, token, tokenIdStr, orderId, opt, tokenName, images,
                tokenName, remarks, result -> {
                    if (result.isSucceed()) {
                        mLegalTenderAppeal.setValue(Resource.success(result, result.getMsg()));
                    } else {
                        mLegalTenderAppeal.setValue(Resource.error(result.getMsg()));
                    }
                });

        return mLegalTenderAppeal;
    }

    public MutableLiveData<Resource<Integer>> uploadFile(ImageView imageView) {
        String base64 = Androids.toBase64(imageView);
        mUpdateImageLiveData.setValue(Resource.loading());
        DataRepository.get().uploadFile(base64, result -> {
            if (result.isSucceed()) {
                mImageList.add(result.getData().getPath());
                mUpdateImageLiveData.setValue(Resource.error(result.getMsg()));
            } else {
                mUpdateImageLiveData.setValue(Resource.error(result.getMsg()));
            }
        });

        return mUpdateImageLiveData;
    }
}
